var totalPage;//总页码
var currentPage = 1;//当前页
var pageSize = 5;//显示条数
var operid = -1;
var tr,id,delAll;
var obj = getSessionData('employeesArr');
var objDepart = getSessionData('departmentsArr');
tableList();
delEvent();
delAllEvent();
pageCreate();
pageChange();
checkAll();
isCheckAll();
addEvent();
search();
change();
length();
inputText();
//显示列表
function tableList(){
        $('tbody').html('');
        var start = (currentPage - 1)* pageSize;
        var end = start + pageSize;
                for (var i = start;i<end && i < obj.length; i++) {
                        for (var m = 0; m < objDepart.length; m++) {
                                  if(obj[i].bmNo === objDepart[m].id){
                                  var k = objDepart[m].name;
                                  break;
                             }else {
                                           k = '待定'
                                  }
                        }


                        $('tbody').append(`
            <tr>
                <td><input type="checkbox" data-id="${obj[i].id}"></td>
                <td class="id">${obj[i].id}</td>
                <td class="name">${obj[i].name}</td>
                <td class="sex">${obj[i].sex}</td>
                <td class="position">${obj[i].position}</td>
                <td class="buMen">${k}</td>
                <td class="tel">${obj[i].tel}</td>
                <td class="birthday">${obj[i].birthday}</td>
                <td class="level">${obj[i].level}</td>
                <td>
                    <span class="iconfont icon-bianji"  data-id='${i}'></span>
                    <span class="iconfont icon-shanchu spnDel" data-id="${obj[i].id}"></span>
                </td>
            </tr>
                `)

                }
        setSessionData('employeesArr',obj);

}
//数据条数
function length(){
        var txt = obj.length;
         $('.length').text(txt);
}
// 得到浏览器中的数据     str:数组名
// var str = JSON.stringify('employeesArr')//将数组/对象转化为字符串
// var obj = JSON.parse(str);//将字符串转化为数组/对象
function getSessionData(str) {
        if(sessionStorage.getItem(str)) {         //浏览器中存在该数组

        }else if(str === "employeesArr"){              //不存在，初识化
                sessionStorage.setItem(str,JSON.stringify(employeesArr));
        }else if(str === 'departmentsArr'){
                sessionStorage.setItem(str,JSON.stringify(departmentsArr));
        }
        var obj = JSON.parse(sessionStorage.getItem(str));
        return obj;
}
//将数据存储到浏览器      str:数组名  data:数组
function setSessionData(str,data) {
        var newStr = JSON.stringify(data);
        sessionStorage.setItem(str,newStr);
}
//单个删除Dom
function delEvent(){
        $('tbody').on('click','.spnDel',function (){
                delAll = 0;
                tr = $(this).parent().parent();
                id =  $(this).attr('data-id');
                $('#delBg').show();
        })
        $('.btnSure').click(function (){
                if(delAll === 0){
                        tr.remove();
                        delArr(id);

                }else {
                        $('tbody input').each(function (index,item){
                                var idAll = $(item).attr('data-id');
                                if(item.checked){
                                        $(item).parent().parent().remove();
                                        delArr(idAll);

                                }
                        })
                }
                $('.modal').hide();
                pageCreate();
                tableList();
                isCheckAll();
        })
        $('.btnCancel').click(function (){
                $('#delBg').hide();
        })
}
//批量删除Dom
function delAllEvent(){
        $('.btnDelAll').click(function (){
                delAll = -1;
                $('#delBg').show();
        })
        $('.btnCancel').click(function (){
                $('#delBg').hide();
        })

}


//删除数组数据
function delArr(id){
        for (var i = 0; i < obj.length; i++) {
                if(obj[i].id === id){
                        obj.splice(i,1);
                        // setSessionData('employeesArr',obj);
                        // setEditInfo(obj[i].name);
                        break;
                }
        }
        length();
}
//生成页码
function pageCreate(){
        var totalSize = obj.length;
        totalPage = Math.ceil(totalSize/pageSize);
        if(currentPage > totalPage){
                currentPage = totalPage;
        }
        $('.divPage').html('');
        for (var i = 1; i <=totalPage ; i++) {
                if(i==currentPage){
                        $('.divPage').append(`
                        <button class="btnPage de_pageBtActive">${i}</button>
                        `)
                }else {
                        $('.divPage').append(`
                        <button class="btnPage">${i}</button>
                `)
                }

        }
}
//换页
function pageChange(){
        $('.divPage').on('click','.btnPage',function (){
                $(".de_pageBt button").each(function () {
                        $(this).attr("class","");        //清空所有按钮的点击class属性
                });
                $(this).addClass("de_pageBtActive");
                currentPage = Number($(this).text());
                tableList();
                pageCreate();
                isCheckAll()
                length();
        })
}

//全选
function checkAll(){
        $('.btnCheckAll').click(function (){
                $('table').find('input').prop('checked',this.checked)
        })
}
//判断全选
function isCheckAll(){
        $('.btnCheckAll').prop('checked',false);
        $('table').on('click','tbody input',function (){
                var isFlag = true;
                $('tbody input').each(function (index,item){
                        if(!item.checked){
                                isFlag = false;
                        }
                })
                $('.btnCheckAll').prop('checked',isFlag);
        })
}
//添加
function addEvent(){
        $('.btnAdd').click(function (){
                operid= -1;
                $('#addBg').show();
                $('.addModal')[0].reset();
        })
        $('.btnSave').click(function (){
                var span = $('.addModal input[type = text]').next().text()
                var id = $('#eId').val();
                var name = $('#eName').val();
                var sex =  $('input[name = sex]:checked').val();
                var position = $('#ePosition').val();
                var buMen = $('#buMen').val();
                var eTel = $('#eTel').val();
                var birthday = $('#calendar').val();
                var level = $('#level').val();
                var content = {"id":id,"bmNo":buMen,"name":name,"sex":sex,"position":position,"tel":eTel,"birthday":birthday,"level":level}
                if(operid === -1){
                        if(id !=='' && name !==''&& position !==''&& buMen !==''&& eTel !=='' && span === ''){
                                obj.push(content);
                                length();
                                pageCreate();
                                $('#addBg').hide();
                                $('input[type = text]').next().text('');
                        }
                }else {
                        if(span === ''){
                                obj.splice(operid,1,content);
                                // setEditInfo(content.name);
                                $('#addBg').hide();
                        }
                }
                tableList();

        })
        $('.btnCancel').click(function (){
                $('#addBg').hide();
                $('input[type = text]').next().text('');
        })
}
//查找
function search(){
        $('.btnSearch').click(function (){
                var val =  $('.iptSearch').val();
                // $('tbody tr').hide().filter(':contains('+val+')').show();
                if(val !== ''){
                        $('tbody').html('');
                        $.each(obj,function (index,item){
                                if(item.name.indexOf(val) !== -1 || item.position.indexOf(val) !== -1){
                                        for (var m = 0; m < objDepart.length; m++) {
                                                if(item.bmNo === objDepart[m].id){
                                                        var k = objDepart[m].name;
                                                        break;
                                                }else {
                                                        k = '待定'
                                                }
                                        }
                                        $('tbody').append(`
                                        <tr>
                                                <td><input type="checkbox" data-id="${item.id}"></td>
                                                <td class="id">${item.id}</td>
                                                <td class="name">${item.name}</td>
                                                <td class="sex">${item.sex}</td>
                                                <td class="position">${item.position}</td>
                                                <td class="buMen">${k}</td>
                                                <td class="tel">${item.tel}</td>
                                                <td class="birthday">${item.birthday}</td>
                                                <td class="level">${item.level}</td>
                                                <td>
                                                    <span class="iconfont icon-bianji"  data-id='${index}'></span>
                                                    <span class="iconfont icon-shanchu spnDel" data-id="${item.id}"></span>
                                                </td>
                                         </tr>
                                        `)
                                }
                        })
                        var searchTxt = $('tbody tr').length;
                        $('.length').text(searchTxt);
                }
        })
}
$('.iptSearch').keyup(function (){
        var e = window.event || arguments[0];
        if (e.keyCode === 13){
                $('.btnSearch').click();
        }
})
//修改
function change(){
        $('tbody').on('click','.icon-bianji',function (){
                var index = parseInt($(this).attr('data-id'));
                operid = index;
                $('#addBg').show();
                $('#eId').val(obj[index].id);
                $('#eName').val(obj[index].name);
                if(obj[index].sex === '男'){
                        $('input[value = 男]').prop('checked','checked');
                }else {
                        $('input[value = 女]').prop('checked','checked');
                }
                $('#ePosition').val(obj[index].position);
                $('#buMen').val(obj[index].bmNo);
                $('#eTel').val(obj[index].tel);
                $('#calendar').val(obj[index].birthday);
                if(obj[index].level === '本科'){
                        $('option[value = 本科]').prop('selected','selected');
                }else if(obj[index].level === '专科'){
                        $('option[value = 专科]').prop('selected','selected');
                }else if(obj[index].level === '高中'){
                        $('option[value = 高中]').prop('selected','selected');
                }else if(obj[index].level === '研究生'){
                        $('option[value = 研究生]').prop('selected','selected');
                }
        })

}
//正则
function inputText(){
        var id = /^e\d{3}$/;
        var name = /^[\u4e00-\u9fa5]{2,6}$/;
        var position = /^\S+$/;
        var buMen = /^d\d{3}$/;
        var eTel =/^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
        check($('#eId'),id);
        check($('#eName'),name);
        check($('#ePosition'),position);
        check($('#buMen'),buMen);
        check($('#eTel'),eTel);
}
function check(input,reg){
        input.blur(function (){
                if(reg.test( $(this).val())){
                        $(this).next().text('');
                }else {
                        $(this).next().text('格式有误').css('color','red');
                }
        })
        $('#eId').blur(function (){
                var id = $('#eId').val();
                console.log(operid);
                if(operid === -1){
                        for (var i = 0; i < obj.length ;i++) {
                                if(obj[i].id === id){
                                        $('#eId').next().text('id已存在').css('color','red');
                                }
                        }
                }else {
                        for (var j = 0; j < obj.length ;j++) {
                                if(obj[operid].id === id){
                                        $('#eId').next().text('');
                                }else if(obj[j].id ===id){
                                        $('#eId').next().text('id已存在').css('color','red');
                                }
                        }
                }

        }).focus(function (){
                $(this).next().text('例：e000').css('color','#9E9E9E');
        })
        $('#eName').focus(function (){
                $(this).next().text('3-6个文字').css('color','#9E9E9E');
        })
        $('#buMen').focus(function (){
                $(this).next().text('例：d000').css('color','#9E9E9E');
        })
        $('#ePosition').focus(function (){
                $(this).next().text('请填写职务').css('color','#9E9E9E');
        })
         $('#eTel').focus(function (){
                 $(this).next().text('11位手机号').css('color','#9E9E9E');
         })

}
